<?php
namespace App\Repos;

use App\Models\Order;
use App\Models\OrderProduct;
use App\Models\OrderProcess;
use App\Models\OrderPoint;
use App\Models\OrderRefund;
use App\Models\Product;
use App\Models\ProductSpec;
use App\Models\UserAddress;
use App\Models\OrderGroup;
use App\Services\RedisService;
use App\Services\WechatTpl;
use EasyWeChat;
use function EasyWeChat\Kernel\Support\generate_sign;
use DB;
use Log;
use Carbon\Carbon;

class OrderRepo
{
	// 后台订单分页
	public static function  paginate($where=[],$num=6,$orderBy='id',$orderWay='desc')
	{
		$query = Order::query();
		if(array_get($where,'status')) {
			$status = array_pull($where,'status');
			if($status==1){
				$query->where('status',1);
			}elseif($status==2) {
				// 待成团

				$query->where('status',50);
			}elseif($status==3) {

				// 待发货
				$query->whereIn('status',['2','3','60']);
			}elseif($status==4){
				// 待收货 待核销
				$query->where('status',4);
				
			}elseif($status==5){
				// 已取消或者已完成
				$query->whereIn('status',['-1','-50','100']);
			}
		}
		if(array_get($where,'keywords')) {
			$keywords = $where['keywords'];
			$query->where('keywords','like','%'.$keywords.'%');
		}
		$list = $query->where($where)					
	  				->with('products','address')
	  				->orderBy($orderBy,$orderWay)
	  				->paginate($num); 
	  	return $list;  
	}

	

	// 用户端订单分页
	public static function  pages($where=[],$num=5,$orderBy='id',$orderWay='desc')
	{	   
		$query = Order::query();
		if(array_get($where,'status')) {
			$status = array_pull($where,'status');
			if($status==1){
				$query->where('status',1);
			}elseif($status==2) {
				// 待成团

				$query->where('status',50);
			}elseif($status==3) {
				
				// 实物拼团待发货
				$query->whereIn('status',['2','3','55']);
			}elseif($status==4){
				// 待收货 待核销
				// 4 单独购买 60拼团成功
				$query->whereIn('status',['4','60']);
				
			}elseif($status==5){
				// 已取消或者已完成
				$query->whereIn('status',['-1','-3','-50','100']);
			}
		}
		$query->select(['id','shop_id','status','total_price','product_type','group_code','code']);
		$list = $query->with(['products:order_id,product_id,product_name,product_thumb,product_num,product_price,product_spec,coupon_code,validity_end,validity_begin','shop:id,name'])
				->where($where)
				->orderBy($orderBy,$orderWay)
	  			->paginate($num); 
	  				
	  	return $list;     
	}

	// 用户端订单分页
	public static function  pagesByShop($where=[],$num=5,$orderBy='id',$orderWay='desc')
	{	   
		$query = Order::query();
		if(array_get($where,'status')) {
			$status = array_pull($where,'status');
			if($status==1){
				//$query->where('status',1);
			}elseif($status==2) {
				// 待发货
				$query->whereIn('status',['2','3','60']);
			}elseif($status==3){
				// 待收货 待核销
				$query->whereIn('status',['4']);
				
			}elseif($status==4){
				// 已取消或者已完成
				$query->whereIn('status',['-1','100']);
			}
		}
		$list = $query->with(['products','shop'])
				->where($where)
				->orderBy($orderBy,$orderWay)
	  			->paginate($num); 
	  				
	  	return $list;     
	}

	public static function find($where)
	{		
		$order = Order::where($where)->with('products','address','shop','products.product')->first();
		return $order;
	}

	/**
	 * 创建单独购买订单
	 */
	public static function create($data)
	{	
		$rs['status'] = false;
		$openid        = array_pull($data,'openid');
		$product_id      = (int)array_pull($data,'product_id');
        $product_num     = (int)array_pull($data,'product_num');
        $product = Product::find($product_id);  
       	$price = $product->price;
       	
       	

        $spec_id = array_pull($data,'spec_id');
        $spec_name = $price = '';
	    if($spec_id) {
	        $spec = ProductSpec::where('id',$spec_id)->first();
	        $spec_name = $spec->spec_name; 
	        $price = $spec->spec_price;
	       
	       
	    }  
	   
		try {
			DB::beginTransaction();
        	
	        // 单独购买
	        
	        $total_amount = $price * $product_num;
	       	
	       	$data['shop_id']      = $product->shop_id;
	        $data['total_price']  = $total_amount;
	        $data['total_amount'] = $total_amount;
	        $data['status']      = 1;
	        $data['code']        = date('YmdHis');
	        $data['remark'] = $data['remark'];
	        if(array_get($data,'agent_id')) {
	            $data['agent_id'] = $data['agent_id'];
	        }
        
	        // 地址
	        if($product->type==1) {
	        	if(!array_get($data,'address_id')) {
	        		$rs['msg'] = '请选择收货地址';
	        		return $rs;
	        	}
	            $address = UserAddress::find($data['address_id']);
	            $data['truename'] = $address->truename;
	            $data['mobile']   = $address->mobile;
	            $data['address']  = $address->city.' '.$address->address;
	        }
        
	        $data['form_id']      = $data['form_id'];
	        $data['product_type'] = $product->type;
	        $data['keywords'] = array_get($data,'truename').'-'.array_get($data,'mobile').'-'.$data['code'].'-'.object_get($product,'shop.name');
	        $data['product_cate_id'] = $product->cate_id;
	        $order = Order::create($data);
	        
	        
        

            $op['order_id']    = $order->id;
            $op['product_id']  = $product_id;
            $op['product_num'] = $product_num;
            $op['product_price'] = $price;
            $op['product_name']  = $product->name;
            $op['product_thumb'] = $product->thumb;
            $op['product_type'] = $product->type;
            $op['validity_begin'] = $product->validity_begin;
            $op['validity_end']   = $product->validity_end;

            if($product->type==2) {
            	$op['coupon_code'] = date('Ymd').strtoupper(str_random(2)).mt_rand(100,999);
            }
            $op['product_spec']  = $spec_name;
            $op['spec_id']     = $spec_id;
            $op['subtotal']      = $total_amount;
            $op['type']          = 1;
            OrderProduct::create($op);       
                
	        //  只有金额大于0才会调用支付
	        if($data['total_price']>0) {
	            $unifyData['openid']       = $openid;
	            $unifyData['total_price']  = $data['total_price'];
	            $unifyData['code']         = $data['code'];
	            $unifyData['order_id']     = $order->id;
	           
	            $rs['status'] = true;
	            $rs['data'] =  self::wechatUnifyOrder($unifyData); 
	            

	        }
			DB::commit();
			return $rs;
		} catch (\Exception $e) {
			dd($e->getMessage());			
			DB::rollBack();
			return $rs;
		}

		return $rs;
	}

	/**
	 * 创建单独购买订单
	 */
	public static function createGroup($data)
	{	
		$rs['status'] = false;
		if(array_get($data,'group_code')) {
			$ogWhere['group_code'] = $data['group_code'];
			$ogWhere['status']     = 50;
			$group_num = OrderGroup::where($ogWhere)->count();
			if(!$group_num) {
				$rs['msg'] = '此团已满，请从新开团或者参加其他团';
				return $rs;
			}

			// 不能参加自己的团
			$map['user_id']    = $data['user_id'];
			$map['group_code'] = $data['group_code'];
			$og = OrderGroup::where($map)->first();
			if($og) {
				$rs['msg'] = '您已经加入了此次拼团，谢谢';
				return $rs;
			}
		}
		


		$openid       = array_pull($data,'openid');
		$product_id   = (int)array_pull($data,'product_id');
		$product_num  = (int)array_pull($data,'product_num');
		$product      = Product::find($product_id);

		$price        = $product->group_price;
		      
        $spec_id      = array_pull($data,'spec_id');
        $spec_name = '';
	    if($spec_id) {
	        $spec = ProductSpec::where('id',$spec_id)->first();
	        $spec_name = $spec->spec_name;
	        $total_amount = $spec->spec_group_price * $product_num;  
	        $price =   $spec->spec_group_price;
	    }

	    if(empty(array_get($data,'group_code'))) {
	    	$data['group_code'] = $product->id.'GC'.date('YmdHis');
	    }   
       
		try {
			DB::beginTransaction();
        	
	            
	        $total_amount = $price * $product_num; 
	       	
	       	$data['shop_id']      = $product->shop_id;
	        $data['total_price']  = $total_amount;
	        $data['total_amount'] = $total_amount;
	        $data['status']      = 1;
	        $data['code']        = date('YmdHis');
	        $data['remark'] = $data['remark'];
	        if(array_get($data,'agent_id')) {
	            $data['agent_id'] = $data['agent_id'];
	        }
        
	        // 地址 实物才需要地址
	        if($product->type == 1 ) {
	        	if(!array_get($data,'address_id')) {
	        		$rs['msg'] = '请选择收货地址';
	        		return $rs;
	        	}
	            $address = UserAddress::find($data['address_id']);
	            $data['truename'] = $address->truename;
	            $data['mobile']   = $address->mobile;
	            $data['address']  = $address->city.' '.$address->address;
	        }
        
	        $data['form_id'] = $data['form_id'];
	        $data['type']    = 2;
	        $data['product_type'] = $product->type;


	        $data['keywords'] = array_get($data,'truename').'-'.array_get($data,'mobile').'-'.$data['code'].'-'.object_get($product,'shop.name');
	        $data['product_cate_id'] = $product->cate_id;
	        $order = Order::create($data);    
        

            $op['order_id']    = $order->id;
            $op['product_id']  = $product_id;
            $op['product_num'] = $product_num;
            $op['product_price'] = $price;
            $op['product_name']  = $product->name;
            $op['product_thumb'] = $product->thumb;
            $op['product_spec']  = $spec_name;
            $op['spec_id']       = $spec_id;
            $op['product_type']  = $product->type; // 实物，费券等
            $op['validity_begin'] = $product->validity_begin;
            $op['validity_end']   = $product->validity_end;
            if($product->type==2) {
            	$op['coupon_code'] = date('Ymd').strtoupper(str_random(2)).mt_rand(100,999);
            }
            $op['subtotal']      = $total_amount;           
            $op['type']          = 2; // 1单独购买 2拼团
            OrderProduct::create($op);       
                
	        //  只有金额大于0才会调用支付
	        if($data['total_price']>0) {
	            $unifyData['openid']       = $openid;
	            $unifyData['total_price']  = $data['total_price'];
	            $unifyData['code']         = $data['code'];
	            $unifyData['order_id']     = $order->id;
	            $unifyData['group_code'] = $order->group_code;
	            $unifyData['is_group'] = 1;    
	            $rs['status'] = true;
	            $rs['data'] =  self::wechatUnifyOrder($unifyData);	
	                      

	        }
			DB::commit();
			return $rs;
		} catch (\Exception $e) {
			dd($e->getMessage());			
			DB::rollBack();
			return $rs;
		}

		return $rs;
	}

	


	

	/**
	 * 发货
	 */
	public static function send($data)
	{
		$rs['status']   = false;
		$rs['msg']      = '操作失败';
		$data['status'] = 4;
		$data['dispatched_at'] = date('Y-m-d H:i:s');
	   
		DB::beginTransaction();
		try{
			$order = Order::where(['id'=>$data['id']])->update($data);
			$process['order_id']     = $data['id'];
			
			$process['order_status'] = $data['status'];
			$process['remark']       = '已填写快递信息';
			$flag = OrderProcess::create($process);	

			
			

			DB::commit();
		} catch(\Exception $e) {
			DB::rollBack();
			Log::info('确认订单发生异常'.$e->getMessage());
			$rs['msg'] = $e->getMessage();
			return $rs;
		}
		
		//dd($order);
		if($flag) {
			$rs['status'] = true;
			$rs['msg']    ='操作成功';


			// $msg    = $order->toArray();
			// $msg['product_info'] = OrderRepo::productInfo($order->id);
			// $msg['openid'] = $order->user->small_openid;
			// WechatTpl::sendTplMsg('send',$msg); 
			return $rs;
		}
		return $rs;
		

	}

	

	/**
	 * 消费券核销
	 */
	public static function hexiao($data)
	{
		$rs['status'] = false;
		$rs['msg']    = '核销操作成功';
		$order_status = 100;
		DB::beginTransaction();
		try{
			$order = Order::find($data['order_id']);
			//dd($order);
			if($order->product_type!=2) {
				$rs['msg'] = '订单类型错误';
				return $rs;
			}
			
			$order->status = $order_status;
			$order->save();
			$process['order_id']     = $data['order_id'];
			$process['shop_user_id'] = $data['shop_user_id'];
			$process['order_status'] = $order_status;
			$process['remark']       = '卖家已核销';
			$flag = OrderProcess::create($process);	
			DB::commit();
		} catch(\Exception $e) {
			DB::rollBack();
			$rs['msg'] = $e->getMessage();
			return $rs;
		}
		
		if($flag) {
			$rs['status'] = true;
			return $rs;
		}
		return $rs;
		

	}

	

	

	/**
	 * 用户手动取消订单
	 */
	public static function cancle($data)
	{
		$rs['status'] = false;
		$where['id'] = $data['order_id'];	
		$order = Order::where($where)->first();
		
		if(!$order) {			
			$rs['msg'] = '订单不存在';
			return $rs;
		}
		
		// 未支付或者未成团的订单才可以取消
		DB::beginTransaction();
		try {
			if($order->status==1 || $order->status==50) {
				// 待确认订单不需要审核
				$order->status = '-2';	
			} 
			
			$order->save();
			
			// 拼团状态修改
			$ogWhere['order_id'] = $data['order_id'];
			OrderGroup::where($ogWhere)
						->update(['status'=>'-2']);
			

			// 如果已经支付 那么要退款
			Log::info('用户自己取消未确认的订单：'.$order->id.'----'.$order->transaction_id);
			
			$process['order_id']     = $order->id;
			$process['order_status'] = -2;
			$process['remark']       = '用户手动取消';
			$flag = OrderProcess::create($process);
			

			
			
			DB::commit();
		} catch (\Exception $e) {
			DB::rollBack();
			$rs['msg'] = $e->getMessage();
			Log::info('取消订单失败：'.$e->getMessage());
			return $rs;
		}
		
		$rs['status'] = true;
		return $rs;	
	}

	
	public static function wechatUnifyOrder($data)
	{
		$payment  = EasyWeChat::payment(); // 微信支付
		$signData = [
		    'body'         => '博美拼团',
		    'out_trade_no' => $data['code'],
		    'trade_type'   => 'JSAPI',  // 必须为JSAPI
		    'openid'       => $data['openid'], // 这里的openid为付款人的openid
		    'total_fee'    => $data['total_price'], // 总价单位分
		    'timeStamp' => time(),
		    'notify_url' => config('app.url').'/wx/pay-notify',
		];

		if(array_get($data,'is_group')) {
			$signData['notify_url'] = config('app.url').'/wx/group-pay-notify';
		}


		$result = $payment->order->unify($signData);
//dd($result);
		// 如果成功生成统一下单的订单，那么进行二次签名
		if ($result['return_code'] === 'SUCCESS') {

			
			$order = Order::find($data['order_id']);
			$order->prepay_id = $result['prepay_id'];
			$order->save();	
			
			

		    // 二次签名的参数必须与下面相同
		    $params = [
		        'appId'     => config('wechat.mini_program.default.app_id'),
		        'timeStamp' => time(),
		        'nonceStr'  => $result['nonce_str'],
		        'package'   => 'prepay_id=' . $result['prepay_id'],
		        'signType'  => 'MD5',
		    ];
		    // config('wechat.payment.default.key')为商户的key
		    $params['paySign'] = generate_sign($params, config('wechat.payment.default.key'));
		    $params['signJs'] = $result['sign'];
		    $params['order_id']      = $data['order_id'];
		    $params['order_code']    = $data['code'];
		    $params['group_code']    = array_get($data,'group_code');
		    $params['order_created'] = date('Y-m-d H:i:s');
		    return $params;
		} else {
			$rs['param'] = $data;
			$rs['result'] = $result;
		    return $rs;
		}
	}

	


	
	public static function total($where)
	{
		$today =  Order::where($where)->whereDate('created_at', '=', date('Y-m-d'))->sum('total_money');
		$all = Order::where($where)->sum('total_money');
		$data['today'] = $today;
		$data['all'] = $all;
		return $data;
	}

	

	


	public static function orderCount($where=[])
	{
		$query = Order::query();
		if(array_get($where,'user_id')) {
			$query->where('user_id',$where['user_id']);
		}
		if(array_get($where,'status')) {
			$status = $where['status'];
			$query->whereIn('status',$status);
		}
		return $query->count();
		
	}

	public static function orderAmount()
	{
		$total = Order::sum('total_price');
		return $total/100;	
	}

	// 退款
	public static function refund($data)
	{
		$rs['status'] = false;
		$order = Order::find($data['id']);
		if($order) {			
			$or['order_id'] = $data['id'];
			$or['remark']   = $data['remark'];
			$or['user_id']  = $order->user_id;
			$flag = OrderRefund::create($or);
			if($flag){
				$order->status = '-100';
				$order->save();
				$rs['status']  = true;

				// 推送模板消息
				$msg    = $order->toArray();
				$msg['remark'] = $data['remark'];
				$msg['openid'] = $order->user->small_openid;
				WechatTpl::sendTplMsg('refund',$msg);
				return $rs;	
			} 
		} else {
			$rs['msg'] = '订单不存在';
		}
		return $rs;
	}

	public static function productInfo($order_id)
	{
		$products_names = '';
		$products = OrderProduct::where(['order_id'=>$order_id])
						->pluck('product_name');
		if($products) {
			$pros = $products->toArray();
			$products_names = implode(',', $pros);
			return $products_names;
		}

		return $product_names;				


	}

	

	public static function getStatus()
	{
		$order = new Order;
		return $order->status_arr;
	}


	// 超过24小时自动收货
	public static function autoRecived()
	{   
		$where['status'] = 5;
		$orders = Order::where($where)->get();
		DB::beginTransaction();
		try {
			$today = date("Y-m-d H:i:s");
			foreach ($orders as $k => $order) {
				$date = Carbon::parse($order->dispatched_at)->addDays('10');

				if($date>=$day) {
					$od['completed_at'] = date('Y-m-d H:i:s');
					$od['status']       = 100;
					Order::where(['id'=>$order->id])->update($od);
				
					$process['order_id']     = $order->id;
					$process['order_status'] = 100;
					$process['remark']       = '发货后7天订单自动完成';
					$flag = OrderProcess::create($process);
					$rs['status'] = true;	
				}			
			}
			
			DB::commit();
		} catch (\Exception $e) {
			DB::rollBack();
			$rs['msg'] = $e->getMessage();
		}
	}


	/**
	 * 确认完成
	 */
	public static function confirmReceived($data)
	{
		$rs['status'] = false;
		$order_status = '100';
		$where['user_id'] = $data['user_id'];
		$where['id']      = $data['order_id'];
		$order = Order::where($where)->first();
		if(empty($order)) {
			$rs['msg'] = '订单不存在';
			return $rs;
		}	
		$order->status      = $order_status;
		$order->received_at = date('Y-m-d H:i:s');
		$flag = $order->save();
		if($flag) {
			$rs['status'] = true;
			$process['order_id']     = $data['order_id'];
			$process['order_status'] = $order_status;
			$process['remark']       = '用户确认收货';
			$flag = OrderProcess::create($process);	
			
			// 推送消息给用户
			$msg['form_id'] = $data['form_id'];
			$msg['openid']  = $order->user->small_openid;
			$msg['code']    = $order->code;
			$msg['product_info'] = self::productInfo($order->id);
			$msg['shop_name']    = object_get($order,'shop.name');
			$msg['shop_phone']   = object_get($order,'shop.phone');	
			$msg['received_at']  = $order->received_at;
			WechatTpl::sendTplMsg('send',$msg); 

			return $rs;
		}
		$rs['msg'] = '操作失败';
		return $rs;
	}


	// 未付款订单单独付款
	public static function pay($data) 
	{
		$rs['status'] = false;
		
		$order = Order::find($data['order_id']);
		

		if($order->transaction_id) {
			$rs['msg'] = '订单已经支付过，无需再次支付';
			return $rs;
		}

		// 更新code 否则同意下单接口生成不了 prepay_id
		$order->code = date('YmdHis');
		$order->save();

		$openid = object_get($order,'user.small_openid');
		//  只有金额大于0才会调用支付
	    if($order->total_price>0) {
	        $unifyData['openid']       = $openid;
	        $unifyData['total_price']  = $order->total_price;
	        $unifyData['code']         = $order->code;
	        $unifyData['order_id']     = $order->id;
	        $unifyData['group_code']   = $order->group_code;
	        $unifyData['is_group'] = $order->group_code?1:0;      
	        $rs['status'] = true;
	        $rs['data'] =  self::wechatUnifyOrder($unifyData); 
	        return $rs;
	            

	    }

	    return $rs;
	}


	// 未支付订单超过两小时自动取消
	public static function autoCancle()
	{   
		$where['status'] = 1;
		$orders = Order::where($where)->get();
		DB::beginTransaction();
		try {
			$day = date("Y-m-d H:i:s", strtotime( '-2 hour' ) );
			foreach ($orders as $k => $order) {
				
				if($order->created_at<=$day) {
					
					$od['status']       = -2;
					Order::where(['id'=>$order->id])->update($od);
				    $ogWhere['order_id'] = $order->id;
					OrderGroup::where($ogWhere)->update($od);
					$process['order_id']     = $order->id;
					$process['order_status'] = -2;
					$process['remark']       = '超过2小时未支付自动取消';
					$flag = OrderProcess::create($process);
					$rs['status'] = true;	
				}			
			}
			
			DB::commit();
		} catch (\Exception $e) {
			DB::rollBack();
			Log::info('取消订单失败：'.$e->getMessage());
			$rs['msg'] = $e->getMessage();
		}
	}

	public static function autoInvalid($product_id)
	{
		$order_ids = OrderProduct::where(['product_id'=>$product_id])->pluck('order_id');

        Order::whereIn('id',$order_ids)
                ->where('product_type','2')
                ->update(['status'=>'-3']);
        return true;                
	}

	/**
	 * 商户端获取核销商品信息
	 */
	public static function hexiaoInfo($order_id)
	{
		$op = OrderProduct::where(['order_id'=>$order_id])
							->first();

		$data['product_name'] = $op->product_name;
		$data['mobile'] = object_get($op,'order.mobile');
		$data['validate_end'] = object_get($op,'product.validity_end');
		$data['total_price_txt'] = object_get($op,'order.total_price_txt');
		$data['coupon_code'] = $op->coupon_code;
		$data['product_type'] = $op->type;	
		return $data;					

	}

	public static  function hexiaoRecord()
	{
		$where['product_type'] = 2;
		$where['status'] = 100;
		$list = Order::where($where)
						->with('products')
						->paginate(10);
		return $list;
	}




	

	

	
	
	

	
	
	
}